package xyz.bali16.module.activeuser.service;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.bali16.application.config.prop.AuthProp;
import xyz.bali16.application.core.utils.AuthUtils;

import java.util.Set;


//@Service("auth")
@Slf4j
@AllArgsConstructor
@Service("auth")
public class PreAuthorizeService {

    public static final String SUPPER_PERMISSION = "*:*";


    private final AuthProp authProp;

    public boolean permission(String... permissions){
        if(permissions == null || permissions.length == 0){
            return false;
        }

        Set<String> authoritySet = AuthUtils.getAuthoritySet();
        if(authoritySet.isEmpty()){
            return false;
        }
        if(authoritySet.contains(SUPPER_PERMISSION)){
            return true;
        }
        for (String permission : permissions) {
            if(StrUtil.isEmpty(permission)){
                continue;
            }
            if(authoritySet.contains(permission)){
                return true;
            }
        }
        return false;
    }

    public boolean role(String... roleCodes){
        if(roleCodes == null || roleCodes.length == 0){
            return false;
        }
        Set<String> roleCodeSet = Sets.newHashSet(roleCodes);
        String superRoleCode = authProp.getSuperRoleCode();
        if(roleCodeSet.contains(superRoleCode)){
            return true;
        }

        Set<String> currentRoleCodes = AuthUtils.getCurrentRoleIds();
        if(currentRoleCodes.isEmpty()){
            return false;
        }
        for (String roleCode : currentRoleCodes) {
            if(StrUtil.isEmpty(roleCode)){
                continue;
            }
            if(currentRoleCodes.contains(roleCode)){
                return true;
            }
        }
        return false;
    }

}
